# encoding: utf-8
class ProjectsController < ApplicationController
  before_filter :authenticate_user!
  before_action :set_project, only: [:show, :edit, :update, :destroy, :leave]

  # GET /projects
  # GET /projects.json
  def index
    @projects = current_user.projects.active.page(params[:page])
    
    if @projects.blank? 
      redirect_to new_project_path
    end
    
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
    @project_users = @project.users
    @monitoring_files = MonitoringFile.where(:project_id => @project.id).order("created_at DESC").page(params[:page])
    
    @user_project_role = current_user.project_role(@project.id)
  end

  # GET /projects/new
  def new
    @project = Project.new
    
    @projects = Project.active.search(params[:search], params[:field]).page(params[:page])
    
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    
    @count_projects = current_user.projects.count
    if @count_projects >= current_user.max_projects
      redirect_to new_project_path, notice: "이미 생성할수 있는 프로젝트의 갯수가 초과되었습니다."
    else 
      @project = Project.new(project_params)
      @project.created_by = current_user.id 
      
      respond_to do |format|
        if @project.save
          # add user and project mapping in user_projects table
          @up = UserProject.new
          @up.user_id = current_user.id
          @up.project_id = @project.id
          @up.role = User::ROLES[:owner]
          @up.save
          
          format.html { redirect_to projects_path, notice: @project.name + '프로젝트가 생성되었습니다.' }
          format.json { render action: 'show', status: :created, location: @project }
        else
          format.html { redirect_to new_project_path, notice: @project.errors.full_messages }
          format.json { render json: @project.errors, status: :unprocessable_entity }
        end
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: @project.name + '프로젝트 내용이 변경되었습니다.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.deleted_at = Time.now
    
    respond_to do |format|
      if @project.save
        format.html { redirect_to projects_url, notice: @project.name + "프로젝트가 삭제되었습니다." }
        format.json { head :no_content }
      else 
        format.html { render action: 'index' }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  def join_project

    @project = Project.find(params[:project_id])
    
    # check if it already exists
    if UserProject.exists?(:user_id => current_user.id, :project_id => params[:project_id])
      redirect_to new_project_path, notice: '프로젝트 [' + @project.name + '] 에 이미 가입하셨습니다.' 
      
    else 
      # add project
      @count_projects = current_user.projects.count
    
      if @count_projects >= current_user.max_projects
        redirect_to new_project_path, notice: "이미 생성할수 있는 프로젝트의 갯수가 초과되었습니다."
      else  
        respond_to do |format|
          if @project.nil?
            format.html { render action: 'new', notice: '프로젝트 [' + @project.name + '] 은 존재하지 않는 프로젝트입니다.' }
          else
            # save project - user mapping
            @up = UserProject.new
            @up.user_id = current_user.id
            @up.project_id = @project.id
            @up.role = User::ROLES[:viewer]
            @up.save
            format.html { redirect_to projects_path, notice: '프로젝트 [' + @project.name + '] 에 가입되었습니다. ' }
          end
        end
      end
    end
    
  end
  
  def leave
    user_id = params[:user_id].nil? ? current_user.id : params[:user_id]
    @up = UserProject.where("user_id = ? AND project_id = ?", user_id,  @project.id).first 
    if @up.present?  
      @up.destroy
    end 
    respond_to do |format|
      format.html { redirect_to projects_url }
      format.json { head :no_content }
    end
  end
  
  def add_member
    email_address = params[:email]
    # check user
    selected_user = User.where("email = ?", email_address).first 
    
    #@project = Project.find(params[:project_id])
    
    if selected_user
        @up = UserProject.where("user_id = ? AND project_id = ?", selected_user.id, params[:id]).first 
        if @up.nil?
          new_member = UserProject.new
          new_member.user_id = selected_user.id
          new_member.project_id = params[:id]
          new_member.role = params[:role]
          if new_member.save
            redirect_to project_path(params[:id]), notice: "새 멤버가 추가되었습니다."
          else 
            redirect_to project_path(params[:id]), notice: "프로젝트에 멤버추가를 실패하였습니다."
          end 
        else 
          redirect_to project_path(params[:id]), notice: "이미 프로젝트에 가입된 사용자입니다."
        end
        
    else 
      redirect_to project_path(params[:id]), notice: "존재하지 않는 사용자입니다."
    end
    
    
  end
  
  
  def change_role
      @up = UserProject.where("user_id = ? AND project_id = ?", params[:user_id], params[:id]).first 
      @up.role = params[:role]
      if @up.save
        redirect_to project_path(params[:id]), notice: "프로젝트 역할이 변경되었습니다."
      else 
        redirect_to project_path(params[:id]), notice: "프로젝트 역할 변경에 실패하였습니다."
      end 
  end
  
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:name)
    end
end
